<template>
  <BaseChart 
    :option="chartOption" 
    :loading="loading"
    :width="width"
    :height="height"
    @chart-click="handleClick"
    @chart-ready="handleReady"
    ref="chartRef"
  />
</template>

<script setup>
import { ref, computed, onMounted, onUnmounted, watch } from 'vue'
import BaseChart from './BaseChart.vue'

// Props定义
const props = defineProps({
  data: {
    type: Array,
    required: true
  },
  maxDataPoints: {
    type: Number,
    default: 20
  },
  title: {
    type: String,
    default: '实时数据'
  },
  width: {
    type: String,
    default: '100%'
  },
  height: {
    type: String,
    default: '200px'
  },
  loading: {
    type: Boolean,
    default: false
  },
  autoUpdate: {
    type: Boolean,
    default: true
  },
  updateInterval: {
    type: Number,
    default: 2000
  },
  colors: {
    type: Array,
    default: () => ['#409EFF', '#67C23A', '#E6A23C', '#F56C6C']
  }
})

// Emits定义
const emit = defineEmits(['chart-click', 'chart-ready', 'data-update'])

// 响应式数据
const chartRef = ref(null)
const timeData = ref([])
const seriesData = ref([])
let updateTimer = null

// 初始化数据
const initData = () => {
  const now = new Date()
  timeData.value = []
  seriesData.value = props.data.map(item => ({
    name: item.name,
    data: []
  }))

  // 生成初始时间点
  for (let i = props.maxDataPoints - 1; i >= 0; i--) {
    const time = new Date(now.getTime() - i * 1000)
    timeData.value.push(time.toLocaleTimeString())
  }

  // 生成初始数据
  props.data.forEach((item, index) => {
    for (let i = 0; i < props.maxDataPoints; i++) {
      const baseValue = item.baseValue || 100
      const variation = (Math.random() - 0.5) * baseValue * 0.2
      seriesData.value[index].data.push(Math.max(0, Math.round(baseValue + variation)))
    }
  })
}

// 更新数据
const updateData = () => {
  const now = new Date()
  
  // 添加新时间点
  timeData.value.push(now.toLocaleTimeString())
  if (timeData.value.length > props.maxDataPoints) {
    timeData.value.shift()
  }

  // 更新每个系列的数据
  seriesData.value.forEach((series, index) => {
    const item = props.data[index]
    const baseValue = item.baseValue || 100
    const variation = (Math.random() - 0.5) * baseValue * 0.2
    const newValue = Math.max(0, Math.round(baseValue + variation))
    
    series.data.push(newValue)
    if (series.data.length > props.maxDataPoints) {
      series.data.shift()
    }
  })

  emit('data-update', {
    timeData: timeData.value,
    seriesData: seriesData.value
  })
}

// 计算属性 - 图表配置
const chartOption = computed(() => {
  const series = seriesData.value.map((item, index) => ({
    name: item.name,
    type: 'line',
    data: item.data,
    smooth: true,
    symbol: 'none',
    lineStyle: {
      width: 2,
      color: props.colors[index % props.colors.length]
    },
    areaStyle: {
      opacity: 0.1,
      color: props.colors[index % props.colors.length]
    }
  }))

  return {
    title: {
      text: props.title,
      left: 'center',
      textStyle: {
        fontSize: 16,
        fontWeight: 'normal',
        color: '#666'
      }
    },
    tooltip: {
      trigger: 'axis',
      backgroundColor: 'rgba(255, 255, 255, 0.95)',
      borderColor: '#e4e7ed',
      borderWidth: 1,
      textStyle: {
        color: '#333'
      },
      axisPointer: {
        type: 'cross'
      }
    },
    legend: {
      data: seriesData.value.map(item => item.name),
      top: 30,
      textStyle: {
        color: '#666',
        fontSize: 14
      }
    },
    grid: {
      left: '5%',
      right: '5%',
      bottom: '8%',
      top: '25%',
      containLabel: true
    },
    xAxis: {
      type: 'category',
      boundaryGap: false,
      data: timeData.value,
      axisLine: {
        lineStyle: {
          color: '#e4e7ed'
        }
      },
      axisLabel: {
        color: '#666',
        fontSize: 12
      }
    },
    yAxis: {
      type: 'value',
      axisLine: {
        show: false
      },
      axisTick: {
        show: false
      },
      axisLabel: {
        color: '#666',
        fontSize: 12
      },
      splitLine: {
        lineStyle: {
          color: '#f0f0f0',
          type: 'dashed'
        }
      }
    },
    series
  }
})

// 开始自动更新
const startAutoUpdate = () => {
  if (props.autoUpdate && !updateTimer) {
    updateTimer = setInterval(updateData, props.updateInterval)
  }
}

// 停止自动更新
const stopAutoUpdate = () => {
  if (updateTimer) {
    clearInterval(updateTimer)
    updateTimer = null
  }
}

// 监听自动更新属性变化
watch(() => props.autoUpdate, (newVal) => {
  if (newVal) {
    startAutoUpdate()
  } else {
    stopAutoUpdate()
  }
})

// 事件处理
const handleClick = (params) => {
  emit('chart-click', params)
}

const handleReady = (instance) => {
  emit('chart-ready', instance)
}

// 生命周期
onMounted(() => {
  initData()
  if (props.autoUpdate) {
    startAutoUpdate()
  }
})

onUnmounted(() => {
  stopAutoUpdate()
})

// 暴露方法
defineExpose({
  updateData,
  startAutoUpdate,
  stopAutoUpdate
})
</script>
